import React, { useState, useEffect } from 'react';
import { 
  Container, Typography, Button, TextField, Table, TableBody, TableCell, 
  TableContainer, TableHead, TableRow, Paper, IconButton, Dialog, 
  DialogTitle, DialogContent, DialogActions, Snackbar, CircularProgress,
  MenuItem
} from '@mui/material';
import { Add as AddIcon, Edit as EditIcon, Delete as DeleteIcon } from '@mui/icons-material';
import { getGoods, addProduct, updateProduct, deleteProduct, getGoodsCategories } from '@/apis/goods';

const AdminProducts = () => {
  const [products, setProducts] = useState([]);
  const [categories, setCategories] = useState([]);
  const [openDialog, setOpenDialog] = useState(false);
  const [currentProduct, setCurrentProduct] = useState({ 
    name: '', 
    description: '', 
    price: '', 
    stockQuantity: '', 
    imageUrl: '', 
    categoryId: '' 
  });
  const [isEditing, setIsEditing] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [snackbar, setSnackbar] = useState({ open: false, message: '' });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchProducts();
    fetchCategories();
  }, []);

  const fetchProducts = async () => {
    try {
      const response = await getGoods();
      const productsData = Array.isArray(response) ? response : response.data;
      setProducts(Array.isArray(productsData) ? productsData : []);
    } catch (error) {
      console.error('获取商品失败:', error);
      setSnackbar({ open: true, message: '获取商品失败' });
      setProducts([]);
    } finally {
      setLoading(false);
    }
  };

  const fetchCategories = async () => {
    try {
      const response = await getGoodsCategories();
      const categoriesData = Array.isArray(response) ? response : response.data;
      setCategories(Array.isArray(categoriesData) ? categoriesData : []);
    } catch (error) {
      console.error('获取商品分类失败:', error);
      setSnackbar({ open: true, message: '获取商品分类失败' });
    }
  };

  const handleOpenDialog = (product = null) => {
    if (product) {
      setCurrentProduct({
        ...product,
        categoryId: product.categoryId || (categories.length > 0 ? categories[0].id : '')
      });
      setIsEditing(true);
    } else {
      setCurrentProduct({ 
        name: '', 
        description: '', 
        price: '', 
        stockQuantity: '', 
        imageUrl: '', 
        categoryId: categories.length > 0 ? categories[0].id : '' 
      });
      setIsEditing(false);
    }
    setOpenDialog(true);
  };

  const handleCloseDialog = () => {
    setOpenDialog(false);
    setCurrentProduct({ name: '', description: '', price: '', stockQuantity: '', imageUrl: '', categoryId: '' });
    setIsEditing(false);
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setCurrentProduct({ ...currentProduct, [name]: value });
  };

  const handleSubmit = async () => {
    try {
      const productData = {
        ...currentProduct,
        categoryId: parseInt(currentProduct.categoryId, 10),
        price: parseFloat(currentProduct.price),
        stockQuantity: parseInt(currentProduct.stockQuantity, 10)
      };
      if (isEditing) {
        await updateProduct(productData.id, productData);
        setSnackbar({ open: true, message: '商品更新成功' });
      } else {
        await addProduct(productData);
        setSnackbar({ open: true, message: '商品添加成功' });
      }
      fetchProducts();
      handleCloseDialog();
    } catch (error) {
      console.error('操作失败:', error);
      setSnackbar({ open: true, message: '操作失败: ' + error.message });
    }
  };

  const handleDelete = async (id) => {
    if (window.confirm('确定要删除这个商品吗？')) {
      try {
        await deleteProduct(id);
        fetchProducts();
        setSnackbar({ open: true, message: '商品删除成功' });
      } catch (error) {
        console.error('删除失败:', error);
        setSnackbar({ open: true, message: '删除失败: ' + error.message });
      }
    }
  };

  const filteredProducts = Array.isArray(products) 
    ? products.filter(product => product.name.toLowerCase().includes(searchTerm.toLowerCase()))
    : [];

  if (loading) {
    return (
      <Container maxWidth="lg" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <CircularProgress />
      </Container>
    );
  }

  return (
    <Container maxWidth="lg">
      <Typography variant="h4" component="h1" gutterBottom>
        商品管理
      </Typography>
      <TextField
        label="搜索商品"
        variant="outlined"
        fullWidth
        margin="normal"
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <Button
        variant="contained"
        color="primary"
        startIcon={<AddIcon />}
        onClick={() => handleOpenDialog()}
        style={{ marginBottom: '20px' }}
      >
        添加商品
      </Button>
      {filteredProducts.length === 0 ? (
        <Typography>暂无商品数据</Typography>
      ) : (
        <TableContainer component={Paper}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>名称</TableCell>
                <TableCell>描述</TableCell>
                <TableCell>价格</TableCell>
                <TableCell>库存</TableCell>
                <TableCell>操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {filteredProducts.map((product) => (
                <TableRow key={product.id}>
                  <TableCell>{product.name}</TableCell>
                  <TableCell>{product.description}</TableCell>
                  <TableCell>{product.price}</TableCell>
                  <TableCell>{product.stockQuantity}</TableCell>
                  <TableCell>
                    <IconButton onClick={() => handleOpenDialog(product)}>
                      <EditIcon />
                    </IconButton>
                    <IconButton onClick={() => handleDelete(product.id)}>
                      <DeleteIcon />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}

      <Dialog open={openDialog} onClose={handleCloseDialog}>
        <DialogTitle>{isEditing ? '编辑商品' : '添加商品'}</DialogTitle>
        <DialogContent>
          <TextField
            select
            margin="dense"
            name="categoryId"
            label="商品分类"
            fullWidth
            value={currentProduct.categoryId}
            onChange={handleInputChange}
          >
            {categories.map((category) => (
              <MenuItem key={category.id} value={category.id}>
                {category.categoryName}
              </MenuItem>
            ))}
          </TextField>
          <TextField
            autoFocus
            margin="dense"
            name="name"
            label="商品名称"
            type="text"
            fullWidth
            value={currentProduct.name}
            onChange={handleInputChange}
          />
          <TextField
            margin="dense"
            name="description"
            label="商品描述"
            type="text"
            fullWidth
            value={currentProduct.description}
            onChange={handleInputChange}
          />
          <TextField
            margin="dense"
            name="price"
            label="价格"
            type="number"
            fullWidth
            value={currentProduct.price}
            onChange={handleInputChange}
          />
          <TextField
            margin="dense"
            name="stockQuantity"
            label="库存数量"
            type="number"
            fullWidth
            value={currentProduct.stockQuantity}
            onChange={handleInputChange}
          />
          <TextField
            margin="dense"
            name="imageUrl"
            label="图片URL"
            type="text"
            fullWidth
            value={currentProduct.imageUrl}
            onChange={handleInputChange}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>取消</Button>
          <Button onClick={handleSubmit} color="primary">
            {isEditing ? '更新' : '添加'}
          </Button>
        </DialogActions>
      </Dialog>

      <Snackbar
        open={snackbar.open}
        autoHideDuration={3000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
        message={snackbar.message}
      />
    </Container>
  );
};

export default AdminProducts;